package com.xishu.controller;

import com.xishu.annotation.valid.MethodValidator;
import com.xishu.entity.Company;
import com.xishu.entity.customer.VipLevel;
import com.xishu.entity.customer.VipRenewMode;
import com.xishu.response.ResponseData;
import com.xishu.response.VerifyUtil;
import com.xishu.service.CommonService;
import com.xishu.service.CompanyService;
import com.xishu.service.CustomerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;

@Api(description = "付费模式设置")
@RestController
public class VipRenewModeController {
    private CompanyService companyService = CompanyService.getInstance();
    private CommonService commonService = CommonService.getInstance();
    private CustomerService customerService = CustomerService.getInstance();

    @ApiOperation(value = "查询餐厅的付费模式")
    @PutMapping(value = ("/vip/renew/mode"), produces = ("application/json;charset=UTF-8"))
    @MethodValidator(mustLogin = false)
    public ResponseData search(@RequestBody VipRenewMode vipRenewMode) throws Exception {
        Long companyId = vipRenewMode.getCompanyId();
        companyService.findCompanyById(companyId);
        VipRenewMode renewMode = companyService.findVipRenewMode(companyId);

        //没有就创建返回
        if (renewMode == null) {
            return commonService.createResponse(companyService.createRenewMode(companyId));
        }

        //有就返回
        return commonService.createResponse(renewMode);
    }

    @ApiOperation(value = "修改餐厅的付费模式")
    @PutMapping(value = ("/vip/renew/mode/modify"), produces = ("application/json;charset=UTF-8"))
    public ResponseData modify(@RequestBody VipRenewMode vipRenewMode) throws Exception {
        Long renewModeId = vipRenewMode.getId();
        VipRenewMode vipRenewModeInDb = commonService.findEntity(renewModeId, VipRenewMode.class);
        Long companyId = vipRenewModeInDb.getCompanyId();
        boolean own = companyService.ownCompany(companyId);
        VerifyUtil.verify(() -> own);

        if (vipRenewMode.getPeriod() != null) {
            //参数校验
            VerifyUtil.verify(() -> Arrays.asList(1, 2).contains(vipRenewMode.getPeriod().intValue()));
        }

        //如果修改了VIP enable,那么修改VIP LEVEL
        if (vipRenewMode.getVipEnable() != null) {
            VipLevel vipLevel = customerService.findVipLevel_company_vip(companyId);
            vipLevel.setEnable(vipRenewMode.getVipEnable());
            commonService.save(vipLevel);

            Company company = companyService.findCompanyById(companyId);
            company.getCompanyConfig().setVipEnable(vipRenewMode.getVipEnable());
            commonService.save(company);
        }

        return commonService.modifyObject(vipRenewMode);
    }
}
